<?php
namespace StarCloud\Services;

use StarCloud\Library\Tool;

class UploadService extends BaseService
{
    protected $endpoint = '';
    protected $accessKeyId = '';
    protected $accessKeySecret = '';
    protected $max_size = 104857600000;
    protected $dir = '';
    protected $host = '';
    protected $callbackUrl = '';

    private static $instance;

    private function __construct()
    {
        $config = self::getConfig()['oss_huoshi'];
        $this->endpoint = $config['endpoint'];
        $this->accessKeyId = $config['accessKeyId'];
        $this->accessKeySecret = $config['accessKeySecret'];
        $this->dir = $config['dir'];
        $this->host = $config['host'];
        $this->callbackUrl = $config['callbackUrl'];
    }

    public function callback(array $arrInput)
    {
        $arrInput['url'] = $this->host . '/' . $arrInput['filename'];
        return $arrInput;
    }

    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function webSign()
    {
        $callback_param = [
            'callbackUrl' => $this->callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded"
        ];

        $callback_string = json_encode($callback_param);
        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 300;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = Tool::gmtIso8601($end);
        $condition = [0 => 'content-length-range', 1 => 0, 2 => $this->max_size];
        $conditions[] = $condition;

        $start = [0 => 'starts-with', 1 => '$key', 2 => $this->dir];
        $conditions[] = $start;

        $arr = ['expiration' => $expiration, 'conditions' => $conditions];
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->accessKeySecret, true));

        $response = [];
        $response['accessid'] = $this->accessKeyId;
        $response['host'] = $this->host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $this->dir;  // 这个参数是设置用户上传文件时指定的前缀。

        return $response;
    }
}
